package com.gitee.wsl.data.store.bundle

import androidx.core.bundle.Bundle
import com.gitee.wsl.data.store.AbstractStoreServer
import kotlin.reflect.KClass

class BundleStoreServer(val state: Bundle): AbstractStoreServer() {

    override fun <T : Any> getOrNull(key: String, type: KClass<T>): T?  {
        if(!isExits(key)) return null
        val value:Any = when(type){
            Long::class -> state.getLong(key)
            String::class -> state.getString(key)?:""
            Int::class -> state.getInt(key)
            Boolean::class -> state.getBoolean(key)
            Float::class -> state.getFloat(key)
            else -> {
                throw IllegalArgumentException("This type can be get into DataStore")
            }
        }
        return value as T
    }

    override fun <T:Any> realPut(key: String, value: T) {
        when (value) {

            // Scalars
            is Boolean -> state.putBoolean(key, value)
            is Byte -> state.putByte(key, value)
            is Char -> state.putChar(key, value)
            is Double -> state.putDouble(key, value)
            is Float -> state.putFloat(key, value)
            is Int -> state.putInt(key, value)
            is Long -> state.putLong(key, value)
            is Short -> state.putShort(key, value)

            // References
            is Bundle -> state.putBundle(key, value)
            is String -> state.putString(key, value)
            is CharSequence -> state.putCharSequence(key, value)

            // Scalar arrays
            is BooleanArray -> state.putBooleanArray(key, value)
            is ByteArray -> state.putByteArray(key, value)
            is CharArray -> state.putCharArray(key, value)
            is DoubleArray -> state.putDoubleArray(key, value)
            is FloatArray -> state.putFloatArray(key, value)
            is IntArray -> state.putIntArray(key, value)
            is LongArray -> state.putLongArray(key, value)
            is ShortArray -> state.putShortArray(key, value)
            else -> throw IllegalArgumentException("This type can be saved into DataStore")
        }
    }


    override fun realRemove(key: String) {
        state.remove(key)
    }

    override fun isExits(key: String): Boolean {
       return state.containsKey(key)
    }
}

